package com.geek.gkpush.framework.retry.queue;

import com.geek.gkpush.framework.retry.model.RetryDelayModel;
import com.geek.gkpush.util.excp.GkPushCodeEnum;
import com.geek.gkpush.util.excp.GkPushException;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <h1>自定义的重试延迟队列。</h1><br/>
 *
 * <h1><br/><a href="https://u.geekbang.org/subject/arch3/100614201">Java 业务架构实战营：https://u.geekbang.org/subject/arch3/100614201</a></h1><br/><h1><a href="https://gitee.com/ylimhhmily/BizArchPracticeCamp">Java 业务架构实战营代码地址：https://gitee.com/ylimhhmily/BizArchPracticeCamp</a></h1><br/><h1><a href="https://u.geekbang.org/subject/java4th/1001148?source=app_share">高级 Java 工程体系课 2023 版：https://u.geekbang.org/subject/java4th/1001148?source=app_share</a></h1><br/><h1><a href="https://time.geekbang.org/column/intro/100312101?tab=catalog">Dubbo 源码剖析与实战：https://time.geekbang.org/column/intro/100312101?tab=catalog</a></h1>
 *
 * @author hmilyylimh
 * ^_^
 * @version 0.0.1
 * ^_^
 * @date 2023/10/3 11:28
 */
public class RetryDelayQueue extends DelayQueue<RetryDelayModel> {

    /** <h2>延迟队列的最大容量，超过该容量的话，就会放不进去，返回失败。</h2> **/
    private int maxCapacity;

    /** <h2>注意这里把引用添加进来，来做到去重复功能，当 bizType + bizValue 一样的话，可极有可能是重复数据还在内存中执行，考虑将新来的丢弃掉。</h2> **/
    private Set<RetryDelayModel> duplicateSet = new HashSet<>();

    /** <h2>控制容量大小的锁，如果超过该容量的话，那就不要放进去了。</h2> **/
    private final ReentrantLock offerLock = new ReentrantLock();

    public RetryDelayQueue(int maxCapacity) {
        this.maxCapacity = maxCapacity;
    }

    /**
     * <h2>向延迟队列添加任务，只要控制添加的个数限制，其余取数据的地方就不用限制最大容量了。</h2>
     *
     * @param: retryDelayModel
     * @return: boolean
     */
    @Override
    public boolean offer(RetryDelayModel retryDelayModel) {
        try {
            offerLock.lock();
            if (size() >= maxCapacity) {
                return false;
            }

            // 如果重复了，就直接丢弃掉
            if (duplicateSet.contains(retryDelayModel)) {
                return false;
            }

            // 不是重复的，继续添加到队列中
            boolean succ = super.offer(retryDelayModel);
            if (succ) {
                duplicateSet.add(retryDelayModel);
            }
            return succ;
        } finally {
            offerLock.unlock();
        }
    }

    /**
     * <h2>向延迟队列添加任务，只要控制添加的个数限制，其余取数据的地方就不用限制最大容量了。</h2>
     *
     * @param: retryDelayModel
     * @param: timeout
     * @param: unit
     * @return: boolean
     */
    @Override
    public boolean offer(RetryDelayModel retryDelayModel, long timeout, TimeUnit unit) {
        try {
            offerLock.lock();
            if (size() >= maxCapacity) {
                return false;
            }

            // 如果重复了，就直接丢弃掉
            if (duplicateSet.contains(retryDelayModel)) {
                return false;
            }

            boolean succ = super.offer(retryDelayModel, timeout, unit);
            if (succ) {
                duplicateSet.add(retryDelayModel);
            }
            return succ;
        } finally {
            offerLock.unlock();
        }
    }

    /**
     * <h2>取出任务数据，因为 offer 方法已经控制了最大容量，这里就无需关心，直接取数据就行了，直接调用父类方法即可。</h2>
     *
     * @param:
     * @return: com.geek.gkpush.framework.retry.model.RetryDelayModel
     */
    @Override
    public RetryDelayModel take() throws InterruptedException {
        RetryDelayModel model = super.take();
        duplicateSet.remove(model);
        return model;
    }

    @Override
    public RetryDelayModel poll() {
        throw new GkPushException(GkPushCodeEnum.UN_SUPPORT_EXCEPTION);
    }

    @Override
    public RetryDelayModel poll(long timeout, TimeUnit unit) throws InterruptedException {
        throw new GkPushException(GkPushCodeEnum.UN_SUPPORT_EXCEPTION);
    }

    @Override
    public void put(RetryDelayModel retryDelayModel) {
        throw new GkPushException(GkPushCodeEnum.UN_SUPPORT_EXCEPTION);
    }

    @Override
    public boolean add(RetryDelayModel retryDelayModel) {
        throw new GkPushException(GkPushCodeEnum.UN_SUPPORT_EXCEPTION);
    }

    @Override
    public boolean addAll(Collection<? extends RetryDelayModel> c) {
        throw new GkPushException(GkPushCodeEnum.UN_SUPPORT_EXCEPTION);
    }
}